package com.example.spring.exercise.security;

import com.example.spring.exercise.entity.UserEntity;
import com.example.spring.exercise.entity.UserRoleEntity;
import com.example.spring.exercise.repository.UserRepository;
import com.example.spring.exercise.repository.UserRoleRepository;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Arrays;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * @author : zhayh
 * @date : 2021-4-18 15:23
 * @description :
 */

@Service
public class UserDetailServiceImpl implements UserDetailsService {
    @Resource
    private UserRepository userRepository;
    @Resource
    private UserRoleRepository userRoleRepository;

    @Override
    public UserDetails loadUserByUsername(String s) throws UsernameNotFoundException {
        // 1. 根据登录名获取用户账户数据
        Optional<UserEntity> userEntityOptional = userRepository.findByLogin(s);
        if (userEntityOptional.isEmpty()) {
            throw new UsernameNotFoundException("登录名" + s + "不存在");
        }
        UserEntity userEntity = userEntityOptional.get();
        // 2. 获取账户对应角色
        List<UserRoleEntity> roles = userRoleRepository.findByUserLogin(userEntity.getLogin());
        // 将角色拼接为数组
        String[] roleNames = roles.stream().map(UserRoleEntity::getRoleName).toArray(String[]::new);
        // 3. 构造为SpringSecurity的验证，并返回交给Spring Security进行校验
        return new User(userEntity.getLogin(), userEntity.getPassword(),
                Arrays.stream(roleNames).map(SimpleGrantedAuthority::new).collect(Collectors.toList()));
    }
}
